const Model = require('../models/library-model')
const ResponseModel = require('../models/response-model')


module.exports = {

    // 查询
    'get::/library/list': async function(ctx) {

        const params = ctx.request.query
        
        const whereBuilder = countQuery => {
            if (params.keyword) {
                countQuery.where('name', 'like', `%${params.keyword}%`)
            }
        }

        const list = await Model.list(Model.buildPaging(params) ,whereBuilder)

        ctx.response.body = ResponseModel.success(list)
    },
    // 保存
    'post::/library/save': async function(ctx) {

        const model = ctx.request.body
        const id = model.id
        delete model.id
        if (id) {
            const updated = await Model.updateBy(model, { id: id })
        } else {
            const inserted = await Model.insert(model)
        }

        ctx.response.body = ResponseModel.success()
    },
    // 更新部分属性
    'post::/library/update': async function (ctx) {

        const { id, order } = ctx.request.body

        if (id) {
            const updateModel = {}
            if (!isNaN(order)) {
                updateModel.order = order
            }
            const updated = await Model.updateBy(updateModel, { id: id })
        }
        ctx.response.body = ResponseModel.success()
    },
    // 删除
    'get::/library/delete/:id': async function(ctx) {

        const { id } = ctx.request.params
        if (id) {
            const deleted = await Model.delete({ id: id })
        }
        ctx.response.body = ResponseModel.success()
    },
    // 选项
    'get::/library/options': async function(ctx) {

        const params = ctx.request.query

        const list = await Model.list(Model.buildPaging(params))

        ctx.response.body = ResponseModel.success(list)
    },
    
}
  